import * as usersService from '../services/users';

export default {
    namespace: 'users',
    state: {
        message: '',
        list: [],
        total: 0,
        page: 0,
    },
    reducers: {
        save(state, { payload: { data: list, total, page } }) {
            return { ...state, list, total, page };
        },
        success(state, { palyload: { message }}){
            return { ...state, message }
        },
        editData(state, { payload: { id } }){
            const { list } = state;
            let temp = list.fliter(item => item.id === id)[0];
            return {
                ...state,
                editItem: {...temp }
            }
        }
    },
    effects: {
        *fetch({ payload: { page } }, { call, put }) {
            const { data, total, pageno } = yield call(usersService.list, { page });
            yield put({ type: 'save', payload: { data, total, page: pageno } });
        },
        *create({ payload: { values } }, { call, put }) {
            const { message } = yield call(usersService.create, { values });
            yield put({ type: 'success', payload: { message } });
        },
        *update({ payload: { values } }, { call, put }) {
            const { message } = yield call(usersService.update, { values });
            yield put({ type: 'success', payload: { message } });
        },
        *remove({ payload: { id } }, { call, put }) {
            const { message } = yield call(usersService.remove, { id });
            yield put({ type: 'success', payload: { message } });
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathname === '/users') {
                    dispatch({ type: 'fetch', payload: {} });
                }
            });
        },
    },
};